//
//  PhotoAlbumTableViewCell.swift
//  selectPhoto
//
//  Created by 孟祥群 on 2018/4/24.
//  Copyright © 2018年 孟祥群. All rights reserved.
//

import UIKit
import Photos

class PhotoAlbumTableViewCell: UITableViewCell {
    let imageSize: CGFloat = 80
    lazy var photoImageView:UIImageView = {
      let imageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 70, height: 70))
       return imageView
    }()
    
    lazy var nameLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 88, y: 21, width: 214, height: 21))
        label.font = UIFont.systemFont(ofSize: 17)
        return label
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 88, y: 45, width: 214, height: 21))
        label.font = UIFont.systemFont(ofSize: 13)
        return label
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI()-> Void {
        self.layoutMargins = UIEdgeInsets.zero
        let bgView = UIView()
        bgView.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.1)
        self.selectedBackgroundView = bgView
        
        self.contentView.addSubview(photoImageView)
        self.contentView.addSubview(nameLabel)
        self.contentView.addSubview(titleLabel)
    }
    
    func renderData(result:PHFetchResult<AnyObject>, label: String?){
        self.nameLabel.text = label
        self.titleLabel.text = String(result.count)
        
        if result.count > 0 {
            if let firstImageAsset = result[0] as? PHAsset {
                let retinaMultiplier = UIScreen.main.scale
                let realSize = self.imageSize * retinaMultiplier
                let size = CGSize(width:realSize, height: realSize)
                
                let imageOptions = PHImageRequestOptions()
                imageOptions.resizeMode = .exact
                
                PHImageManager.default().requestImage(for: firstImageAsset, targetSize: size, contentMode: .aspectFill, options: imageOptions, resultHandler: { (image, info) -> Void in
                    DispatchQueue.main.async {
                        self.photoImageView.image = image
                    }
                })
            }
            
        }
        
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
